// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/store'
import axios from 'axios'
import './assets/less/normaliz.less' //有些浏览器的body标签默认自带8px的margin，引入此css解决各浏览器差异
import MuseUI from 'muse-ui'
import 'muse-ui/dist/muse-ui.css'
import './assets/css/common.css'
import './assets/less/common.less'
import StarRating from 'vue-star-rating'
import Loading from './components/loading'
import util from './util/util'

Vue.use(MuseUI)
Vue.use(Loading)
Vue.config.productionTip = false
Vue.component('star-rating', StarRating);

//测试环境
// const DEBUG_HOST = 'http://120.24.89.166:520';
// const RELEASE_HOST = 'http://119.23.134.227:81';

axios.defaults.timeout = 5000;
// axios.defaults.baseURL = 'http://120.24.89.166:520/ar-social/api/';
axios.defaults.baseURL = util.getHost() + '/ar-social/api/';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';


//关于axios配置，发送请求显示loading，请求回来loading消失
axios.interceptors.request.use(
  function (config) { //配置发送请求的信息
    if (store.state.token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers.Authorization = store.state.token;
      // console.log('token = ' + store.state.token);
    }
    store.dispatch('showLoading');
    return config;
  },

  function (error) {
    util.toast('请求失败');
    console.log(error.message);
    return Promise.reject(error);
  });

axios.interceptors.response.use(
  function (response) { //配置请求回来的信息
    store.dispatch('hideLoading');
    // util.toast('请求成功');
    console.log(response);
    //统一处理错误
    if (response.data.code != '0') {
      util.toast(response.data.msg);
      console.log(response.data.msg);
    }

    return response;
  },

  function (error) {
    // 请求已发出，但服务器响应的状态码不在 2xx 范围内
    store.dispatch('hideLoading');
    util.toast('服务器繁忙');
    console.log(error);

    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 401 清除token信息并跳转到登录页面
          store.dispatch('USER_SIGNOUT');
          store.dispatch('cleanToken');
          router.replace({
            path: 'login'
          })
      }
    }

    return Promise.reject(error);
  });

Vue.prototype.$http = axios; //挂到原型上

router.beforeEach(({
  meta,
  path
}, from, next) => {
  var {
    auth = true
  } = meta;
  var isLogin = Boolean(store.state.token);
  if (auth && !isLogin && path !== '/login') {
    return next({
      path: '/login'
    })
  }
  next();
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: {
    App
  }
})
